package com.mxw.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.mxw.account.dto.AccountDTO;
import com.mxw.account.mapper.AccountRepository;
import com.mxw.account.mapper.domain.AccountEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @Description TODO
 * @Author RingKo
 * @Date 2022/7/29 17:02
 * @Version 1.0
 */
@Slf4j
@Component
public class TestHandler {
  @Autowired AccountRepository accountRepository;
  @Autowired TestHandler testHandler;

  @Transactional
  public AccountEntity jpaTest(AccountDTO accountDTO) throws Exception{
    AccountEntity accountEntity = testHandler.jpaSave(accountDTO);
    log.info("main: " + accountEntity.getId());
    new Thread(() -> testHandler.jpaSave2(accountEntity)).start();
    Thread.sleep(5000);
    // 其他业务处理
    return null;
  }

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public AccountEntity jpaSave(AccountDTO accountDTO) {
    AccountEntity account = BeanUtil.copyProperties(accountDTO, AccountEntity.class);
    return accountRepository.save(account);
  }

  @Transactional
  public AccountEntity jpaSave2(AccountEntity accountEntity) {
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    log.info("thread: " + accountEntity.getId());
    accountEntity.setAmount(accountEntity.getAmount().add(BigDecimal.ONE));
    AccountEntity save = accountRepository.save(accountEntity);
    log.info("thread: " + save.getId());
    return save;
  }
}
